import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.nmix import Mixer
from modules.mixers.qmix import QMixer
from modules.mixers.vdn import VDNMixer
from utils.rl_utils import build_td_lambda_targets, build_q_lambda_targets
import torch as th
from torch.optim import RMSprop, Adam
import numpy as np
from utils.th_utils import get_parameters_num
import torch.nn.functional as F
from components.standarize_stream import RunningMeanStd
from controllers import REGISTRY as mac_REGISTRY    

class CFCQLearner:
    def __init__(self, mac, scheme, logger, args):
        self.args = args
        self.n_agents = args.n_agents
        self.mac = mac
        self.logger = logger
        
        self.params = list(mac.parameters())

        self.mixer = None
        if args.mixer is not None:
            match args.mixer:
                case "vdn":
                    self.mixer = VDNMixer()
                case "qmix":
                    self.mixer = QMixer(args)
                case "nmix":
                    self.mixer = Mixer(args)
                case _:
                    raise ValueError("Mixer {} not recognised.".format(args.mixer))
            self.params += list(self.mixer.parameters())
            self.target_mixer = copy.deepcopy(self.mixer)
    
        match self.args.optim_type.lower():
            case "rmsprop":
                self.optimiser = RMSprop(params=self.params, lr=self.args.lr, alpha=self.args.optim_alpha, eps=self.args.optim_eps, weight_decay=self.args.weight_decay)
            case "adam":
                self.optimiser = Adam(params=self.params, lr=self.args.lr, weight_decay=self.args.weight_decay)
            case _:
                raise ValueError("Invalid optimiser type", self.args.optim_type)
        # a little wasteful to deepcopy (e.g. duplicates action selector), but should work for any MAC
        self.target_mac = copy.deepcopy(mac)

        self.log_stats_t = -self.args.learner_log_interval - 1
        self.training_steps = 0
        self.last_target_update_step = 0
        self.last_target_update_episode = 0

        device = "cuda" if args.use_cuda else "cpu"
        if self.args.standardise_returns:
            self.ret_ms = RunningMeanStd(shape=(self.n_agents,), device=device)
        if self.args.standardise_rewards:
            self.rew_ms = RunningMeanStd(shape=(1,), device=device)
            
    
        self.need_train_behaviour = False
        if getattr(args, "train_behaviour", False):
            self.need_train_behaviour = True
            self.behaviour_training_steps = 0
            self.behaviour_log_stats_t = - self.args.behaviour_log_interval - 1
            
            behaviour_args = copy.deepcopy(args)
            
            
            behaviour_args.mask_before_softmax = True
            behaviour_args.agent = "rnn"
            behaviour_args.agent_output_type = "pi_logits"
            behaviour_args.action_selector = "multinomial"
            behaviour_args.epsilon_start = .0
            behaviour_args.epsilon_finish = .0
            behaviour_args.epsilon_anneal_time = 500000
            
            self.behaviour_mini_epoch = args.behaviour_mini_epoch
            self.behaviour_mac = mac_REGISTRY['basic_mac'](scheme, None, behaviour_args)
            self.behaviour_params = list(self.behaviour_mac.parameters())
            self.behaviour_optimiser = Adam(params=self.behaviour_params, lr=self.args.lr, weight_decay=self.args.weight_decay)
    

    def train_behaviour(self, batch):
        self.behaviour_training_steps += 1
        
        actions = batch["actions"][:, :-1]
        terminated = batch["terminated"][:, :-1].float()
        mask = batch["filled"][:, :-1].float()
        mask[:, 1:] = mask[:, 1:] * (1 - terminated[:, :-1])
        avail_actions = batch["avail_actions"]
        
        mask_agent = mask.unsqueeze(2).repeat(1, 1, self.n_agents, 1)
        # (bs, T, n_agents, 1)
        
        for _ in range(self.behaviour_mini_epoch):
            mac_out = []
            self.behaviour_mac.init_hidden(batch.batch_size)
            for t in range(batch.max_seq_length):
                agent_outs = self.behaviour_mac.forward(batch, t=t)
                mac_out.append(agent_outs)
            mac_out = th.stack(mac_out, dim=1)
            
            mac_out[avail_actions==0] = 1e-10
            pi_taken = th.gather(mac_out, dim=3, index=actions)
            log_pi_taken = th.log(pi_taken)
            
            loss = -(log_pi_taken * mask_agent).sum() / mask_agent.sum()

            self.behaviour_optimiser.zero_grad()
            loss.backward()
            grad_norm = th.nn.utils.clip_grad_norm_(self.behaviour_params, self.args.grad_norm_clip)
            self.behaviour_optimiser.step()
        
    
        if self.behaviour_training_steps - self.behaviour_log_stats_t >= self.args.behaviour_log_interval:
            self.logger.log_stat("bc_loss", loss.item(), self.behaviour_training_steps)
            self.logger.log_stat("bc_grad_norm", grad_norm, self.behaviour_training_steps)
            
            
            self.behaviour_log_stats_t = self.behaviour_training_steps
    
    def train(self, batch, t_env, episode_num):
        rewards = batch["reward"][:, :-1]
        actions = batch["actions"][:, :-1]
        terminated = batch["terminated"][:, :-1].float()
        mask = batch["filled"][:, :-1].float()
        mask[:, 1:] = mask[:, 1:] * (1 - terminated[:, :-1])
        avail_actions = batch["avail_actions"]
        
        if self.args.standardise_rewards:
            self.rew_ms.update(rewards)
            rewards = (rewards - self.rew_ms.mean) / th.sqrt(self.rew_ms.var)
        
        # Calculate estimated Q-Values
        mac_out = []
        self.mac.init_hidden(batch.batch_size)
        for t in range(batch.max_seq_length):
            agent_outs = self.mac.forward(batch, t=t)
            mac_out.append(agent_outs)
        mac_out = th.stack(mac_out, dim=1)  # Concat over time #(bs, T-1, n_agents, n_ac)
        
        mac_out[avail_actions == 0] = -9999999
        # Pick the Q-Values for the actions taken by each agent
        chosen_action_na_qvals = th.gather(mac_out[:, :-1], dim=3, index=actions).squeeze(3)  # Remove the last dim
        
        # Calculate the Q-Values necessary for the target
        target_mac_out = []
        self.target_mac.init_hidden(batch.batch_size)
        for t in range(batch.max_seq_length):
            target_agent_outs = self.target_mac.forward(batch, t=t)
            target_mac_out.append(target_agent_outs)
        
        # We don't need the first timesteps Q-Value estimate for calculating targets
        target_mac_out = th.stack(target_mac_out, dim=1)  # Concat across time

        # Mask out unavailable actions
        target_mac_out[avail_actions == 0] = -9999999
        
        mac_out_detach = mac_out.clone().detach()
        cur_max_actions = mac_out_detach.max(dim=3, keepdim=True)[1]
        target_max_na_qvals = th.gather(target_mac_out, 3, cur_max_actions).squeeze(3)
        cons_max_q_vals = th.gather(mac_out, 3, cur_max_actions).squeeze(3)
        
        chosen_action_qvals = self.mixer(chosen_action_na_qvals, batch["state"][:, :-1])
        target_max_qvals = self.target_mixer(target_max_na_qvals, batch["state"])
        cons_max_q_vals = self.mixer(cons_max_q_vals, batch["state"])
        
        if self.args.standardise_returns:
            target_max_qvals = target_max_qvals * th.sqrt(self.ret_ms.var) + self.ret_ms.mean
        
        match self.args.cal_target:
            case "td_lambda":
                targets = build_td_lambda_targets(rewards, terminated, mask, target_max_qvals, 
                                                            self.n_agents, self.args.gamma, self.args.td_lambda)
            case "raw":
                targets = rewards + self.args.gamma * (1 - terminated) * target_max_qvals[:, 1:]
            case _:
                raise ValueError("Unknown target calculation type")

        if self.args.standardise_returns:
            self.ret_ms.update(targets)
            targets = (targets - self.ret_ms.mean) / th.sqrt(self.ret_ms.var)
        
        td_error = (chosen_action_qvals - targets.detach())

        mask = mask.expand_as(td_error) # (bs, T, )

        # 0-out the targets that came from padded data
        masked_td_error = td_error * mask

        # Normal L2 loss, take mean over actual data
        td_loss = (masked_td_error ** 2).sum() / mask.sum()

        
        
        # CF-CQL loss
        total_random_actions = actions
        lambda_mask = th.ones_like(actions).squeeze(-1) / self.n_agents
        if self.need_train_behaviour:
            beta_prob = []
            self.behaviour_mac.init_hidden(batch.batch_size)
            for t in range(batch.max_seq_length-1):
                agent_outs = self.behaviour_mac.forward(batch, t=t)
                beta_prob.append(agent_outs)
            beta_prob = th.stack(beta_prob, dim=1)
            ratio = []
        
        negative_sampling=[]
        for agent_i in range(self.n_agents):
            noexp_negative_sampling = []
            for action_j in range(self.args.n_actions):
                random_actions = th.concat([total_random_actions[:, :, :agent_i],\
                    th.ones_like(actions[:, :, 0:1]).to(self.args.device) * action_j,\
                    total_random_actions[:, :, agent_i+1:]], dim=2)
                random_chosen_action_qvals = th.gather(mac_out[:, :-1], dim=3, index=random_actions).squeeze(-1)
                random_chosen_action_qtotal = self.mixer(random_chosen_action_qvals, batch["state"][:, :-1])
                random_chosen_action_qtotal[avail_actions[:, :-1, agent_i, action_j] == 0] = -1e10
                noexp_negative_sampling.append(random_chosen_action_qtotal)
            noexp_negative_sampling = th.concat(noexp_negative_sampling, dim=-1)
        
            if self.need_train_behaviour:
                mu_prob = th.nn.functional.softmax(noexp_negative_sampling, dim=-1)#bs,ts,ad
                assert beta_prob[:, :, agent_i].shape == mu_prob.shape
                ratio.append((th.nn.functional.kl_div(th.log(beta_prob[:, :, agent_i]+0.00001), mu_prob+0.00001, reduction='none') * \
                    avail_actions[:, :-1, agent_i]).sum(-1, keepdim=True))
            
            negative_sampling.append(th.logsumexp(noexp_negative_sampling, dim=-1).unsqueeze(-1))
        if self.need_train_behaviour:
            ratio = th.concat(ratio, dim=-1)
            
            if self.args.softmax_temp == 100:
                lambda_mask = th.nn.functional.one_hot(th.argmax(ratio, dim=-1), num_classes=self.n_agents).detach()
            else:
                lambda_mask = th.nn.functional.softmax(ratio * self.args.softmax_temp, dim=-1).detach()
        
        negative_sampling = th.concat(negative_sampling, dim=-1)#bs,ts,na
        negative_sampling = (negative_sampling * lambda_mask).sum(-1, keepdim=True)
        dataset_expec = chosen_action_qvals
        cql_loss = ((negative_sampling-dataset_expec) * mask).sum() /  mask.sum()
        
        loss = td_loss + self.args.global_cql_alpha * cql_loss
        
        self.optimiser.zero_grad()
        loss.backward()
        grad_norm = th.nn.utils.clip_grad_norm_(self.params, self.args.grad_norm_clip)
        self.optimiser.step()
        
        self.training_steps += 1
        if self.args.target_update_interval_or_tau > 1 and (episode_num - self.last_target_update_episode) / self.args.target_update_interval_or_tau >= 1.0:
            self._update_targets_hard()
            self.last_target_update_episode = episode_num
        elif self.args.target_update_interval_or_tau <= 1.0:
            self._update_targets_soft(self.args.target_update_interval_or_tau)

        
        if t_env - self.log_stats_t >= self.args.learner_log_interval:
            self.logger.log_stat("loss", loss.item(), t_env)
            self.logger.log_stat("grad_norm", grad_norm, t_env)
            self.logger.log_stat("td_loss", td_loss.item(), t_env)
            self.logger.log_stat("cql_loss", cql_loss.item(), t_env)
            mask_elems = mask.sum().item()
            self.logger.log_stat("td_error_abs", (masked_td_error.abs().sum().item()/mask_elems), t_env)
            self.logger.log_stat("q_taken_mean", (chosen_action_qvals * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)
            self.logger.log_stat("target_mean", (targets * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)
            self.logger.log_stat("negtive_sampling_mean", ((negative_sampling * mask).sum().item()/mask_elems), t_env)
            if self.need_train_behaviour:
                self.logger.log_stat("lambda_ratio",((ratio * mask).sum().item())/mask_elems, t_env)
                self.logger.log_stat("lambda_mask_max",((lambda_mask.max(-1, keepdim=True)[0] * mask).sum().item())/mask_elems, t_env)
                self.logger.log_stat("lambda_mask_min",((lambda_mask.min(-1, keepdim=True)[0] * mask).sum().item())/mask_elems, t_env)
                self.logger.log_stat("lambda_mask_mean",((lambda_mask * mask).sum().item())/mask_elems, t_env)
                
            self.log_stats_t = t_env
    
    def _update_targets_hard(self):
        self.target_mac.load_state(self.mac)
        if self.mixer is not None:
            self.target_mixer.load_state_dict(self.mixer.state_dict())

    def _update_targets_soft(self, tau):
        for target_param, param in zip(self.target_mac.parameters(), self.mac.parameters()):
            target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)
        if self.mixer is not None:
            for target_param, param in zip(self.target_mixer.parameters(), self.mixer.parameters()):
                target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)

    def cuda(self):
        self.mac.cuda()
        self.target_mac.cuda()
        if self.mixer is not None:
            self.mixer.cuda()
            self.target_mixer.cuda()
        
        if self.need_train_behaviour:
            self.behaviour_mac.cuda()
        

    def save_models(self, path):
        self.mac.save_models(path)
        if self.mixer is not None:
            th.save(self.mixer.state_dict(), "{}/mixer.th".format(path))
        th.save(self.optimiser.state_dict(), "{}/opt.th".format(path))

    def load_models(self, path):
        self.mac.load_models(path)
        # Not quite right but I don't want to save target networks
        self.target_mac.load_models(path)
        if self.mixer is not None:
            self.mixer.load_state_dict(th.load("{}/mixer.th".format(path), map_location=lambda storage, loc: storage))
        self.optimiser.load_state_dict(th.load("{}/opt.th".format(path), map_location=lambda storage, loc: storage))


    def save_behaviour_model(self, path):
        self.behaviour_mac.save_models(path)
        th.save(self.behaviour_optimiser.state_dict(), "{}/behaviour_opt.th".format(path))
    
    def load_behaviour_model(self, path):
        self.behaviour_mac.load_models(path)
        self.behaviour_optimiser.load_state_dict(th.load("{}/behaviour_opt.th".format(path), map_location=lambda storage, loc: storage))
                